package cn.zhz.cloud.auth.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.zhz.cloud.auth.web.mapper.IUserMapper;
import cn.zhz.cloud.auth.web.model.dto.UserQueryDto;
import cn.zhz.cloud.auth.web.model.dto.UserSaveDto;
import cn.zhz.cloud.auth.web.model.po.UserPo;
import cn.zhz.cloud.auth.web.model.vo.UserVo;
import cn.zhz.cloud.auth.web.service.IUserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static cn.zhz.cloud.auth.web.constant.AuthConstant.LOGIN_AES_CRYPTO_KEY_BYTE;

/**
 * 用户 Service实现类
 *
 * @author zhz
 * @since 2022-11-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, UserPo> implements IUserService {


    /**
     * 分页查询
     *
     * @param queryDto 查询参数
     * @return
     */
    @Override
    public Page<UserVo> page(UserQueryDto queryDto) {
        long current = queryDto.getCurrent();
        long pageSize = queryDto.getSize();
        Page<UserPo> userPoPage = baseMapper.selectPage(new Page<>(current, pageSize), Wrappers.lambdaQuery(UserPo.class));
        List<UserVo> userVoList = userPoPage.getRecords().stream().map(userPo -> BeanUtil.copyProperties(userPo, UserVo.class)).collect(Collectors.toList());

        return new Page<UserVo>(current, pageSize)
                .setTotal(userPoPage.getTotal())
                .setRecords(userVoList);
    }

    /**
     * 详情
     *
     * @param id 主键
     * @return
     */
    @Override
    public UserVo info(Long id) {
        UserPo userPo = baseMapper.selectById(id);
        if (userPo == null) {
            // TODO
        }
        return BeanUtil.copyProperties(userPo, UserVo.class);
    }

    /**
     * 保存
     *
     * @param saveDto 保存参数
     * @return 主键
     */
    @Override
    public Long save(UserSaveDto saveDto) {
        UserPo userPo = BeanUtil.copyProperties(saveDto, UserPo.class);
        if (StrUtil.isNotBlank(userPo.getPassword())) {
            String passwordEncrypt = SecureUtil.aes(LOGIN_AES_CRYPTO_KEY_BYTE).encryptBase64(userPo.getPassword());
            userPo.setPassword(passwordEncrypt);
        }
        this.saveOrUpdate(userPo);
        return userPo.getId();
    }

    /**
     * 删除
     *
     * @param id 主键
     */
    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

}
